package pl.koziolekweb.jqr.ui;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;

import pl.koziolekweb.jqr.data.StandardSeparator;
import pl.koziolekweb.jqr.data.StandardSerializer;

public class TextProcessor {

	public static int close() {
		return JFrame.EXIT_ON_CLOSE;
	}

	private String fullText;

	private String[] parsedText;

	private StandardSerializer serializer;

	private Target target;

	private Thread thread = new Thread(new Runnable() {

		@Override
		public void run() {
			int i = 0;
			while (i < parsedText.length) {
				target.update(parsedText[i]);
				try {
					Thread.sleep(300);
					i++;
				} catch (InterruptedException e) {
					break;
				}
			}
		}
	});

	public TextProcessor(Target target) {
		this.target = target;
		fullText = "";
		serializer = new StandardSerializer();
		serializer.setSeparator(StandardSeparator.WORD);
	}

	public void loadFile(File file) throws IOException {
		FileReader fileReader = new FileReader(file);
		int c = -1;
		while ((c = fileReader.read()) > 0) {
			fullText += (char) c;
		}
		fileReader.close();
		parsedText = serializer.serialize(fullText);

	}

	public void loadFile(String path) throws IOException {
		File file = new File(path);
		loadFile(file);
	}

	public void pause() {
	}

	public void start() {
		thread.start();
	}

	public void stop() {
		thread.interrupt();
	}
}
